package cn.stylefeng.guns.modular.business.common;


import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import weixin.popular.api.MessageAPI;
import weixin.popular.bean.message.templatemessage.TemplateMessage;
import weixin.popular.bean.message.templatemessage.TemplateMessageItem;
import weixin.popular.bean.message.templatemessage.TemplateMessageResult;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class BaseAsyncTask {

    @Autowired
    UserMapper userMapper;

    @Async("asyncSendTemplateMessage")
    @Transactional(rollbackFor = RuntimeException.class)
    public void asyncSendTemplateMessage(List<String> userIdList, String templateId, LinkedHashMap<String, TemplateMessageItem> data, String url) {
        userIdList.forEach(openid -> sendWxMessage(templateId, data, openid, url));
    }

    /**
     * 发送微信模板消息
     *
     * @param templateId 模板id
     * @param data       数据
     * @param openid     openid
     */
    private SendResult sendWxMessage(String templateId, LinkedHashMap<String, TemplateMessageItem> data, String openid, String url) {
        TemplateMessage templateMessage = new TemplateMessage();
        templateMessage.setTouser(openid);
        templateMessage.setTemplate_id(templateId);
        templateMessage.setData(data);
        templateMessage.setUrl(url);
        TemplateMessageResult templateMessageResult = MessageAPI.messageTemplateSend(TokenSingleton.getTokenSingleton().getWeixinToken(), templateMessage);
        if (templateMessageResult.isSuccess()) {
            return new SendResult(true, "ok");
        } else {
            log.info("发送微信模板信息失败,openid为：{},异常code:{},异常信息：{}", openid, templateMessageResult.getErrcode(), templateMessageResult.getErrmsg());
            return new SendResult(false, templateMessageResult.getErrmsg());
        }
    }


    private List<String> getOpendids(List<String> userIds) {
        List<User> users = userMapper.selectList(new QueryWrapper<User>().in("user_id", userIds));
        return users.stream().map(user -> user.getUserId().toString())
                .collect(Collectors.toList());
    }

}
